/**
 *  検索条件に応じて書籍情報を取得するクラス
 *  @author Komori
 *  @version 1.0
 */

package book;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.DBManager;

public class SearchServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		req.setCharacterEncoding("UTF-8");

		//	問い合わせ文字列を取得
		String pageUrl = req.getQueryString();
		int index = pageUrl.indexOf("&page=");

		//	検索画面より表示、または、頁番号リンクで表示した場合
		if (index >= 0) {
			//	全てのパラメータを取得
			@SuppressWarnings("unchecked")
			Map<String, String[]> pMap = (Map<String, String[]>)req.getParameterMap();

			//	別のマップへコピー
			Map<String, String[]> m = new HashMap<String, String[]>();
			m.putAll(pMap);

			//	ページ番号より前の問い合わせ文字列を保存
			pageUrl = pageUrl.substring(0,index);
			String[] v = { pageUrl };
			m.put("url",  v  );

			//	ページ番号を保存
			String page = req.getParameter("page");
			String[] p = { page };
			m.put("page", p);

			//	全てのパラメータをセッションに保存
			HttpSession session = req.getSession();
			session.removeAttribute("BookSerchParameter");
			session.setAttribute("BookSerchParameter", m);
		}

		//	検索する
		search(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");

		//	検索する
		search(req, resp);
	}

	private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException  {
		String pageStr = null;
		String title = null;
		String writer = null;
		String publisherId = null;
		String genreId = null;
		String isbn = null;
		String keyword = null;

		//	セッション情報からパラメータを取得
		HttpSession session = req.getSession();
		@SuppressWarnings("unchecked")
		Map<String, String[]> m = (Map<String, String[]>)session.getAttribute("BookSerchParameter");

		String[] titles = (String[])m.get("title");
		String[] writers = (String[])m.get("writer");
		String[] publisherIds = (String[])m.get("publisher");
		String[] genreIds = (String[])m.get("genre");
		String[] isbns = (String[])m.get("isbn");
		String[] keywords = (String[])m.get("keyword");
		String[] pages = (String[])m.get("page");

		title = titles[0];
		writer = writers[0];
		publisherId = publisherIds[0];
		genreId = genreIds[0];
		isbn = isbns[0];
		keyword = keywords[0];
		pageStr = pages[0];


		// パラメータによる書籍検索条件の設定
		StringBuffer where = new StringBuffer();
		if(title != null) {
			if(!"".equals(title) && title.length() > 0) {
				String[] keyAry = convert(title);
			    for (int i=0; i<keyAry.length; i++) {
			    	where.append(" title collate utf8_unicode_ci like '%" + keyAry[i] + "%' and");
			    }
			}
			if(!"".equals(writer) && writer.length() > 0) {
				String[] keyAry = convert(writer);
			    for (int i=0; i<keyAry.length; i++) {
			    	where.append(" writer collate utf8_unicode_ci like '%" + keyAry[i] + "%' and");
			    }
			}
			if(!"".equals(publisherId) && publisherId.length() > 0) {
				where.append(" publisher_id = '" + publisherId + "' and");
			}
			if(!"".equals(genreId) && genreId.length() > 0) {
				where.append(" genre_id = '" + genreId + "' and");
			}
			if(!"".equals(isbn) && isbn.length() > 0) {
				where.append(" isbn = '" + isbn + "' and");
			}
			if(!"".equals(keyword) && keyword.length() > 0) {
				String[] keyAry = convert(keyword);
				// キーワード検索の実装
			    for (int i=0; i<keyAry.length; i++) {
			    	where.append(" content collate utf8_unicode_ci like '%" + keyAry[i] + "%' and");
			    }
			}
			// 何かしらの条件が指定されているか確認しwhere句の完成
			int wl = where.length();
			if(wl > 0) {
				where.delete(wl-4, wl);
				where.insert(0, " where");
			}
		}

		// 書籍件数取得SQL文
		String sqlCnt = "select count(*) as cnt from books" + where;

		Connection con = null;
		Statement smt = null;

		int page;
		try {
			con = DBManager.getConnection();
			smt = con.createStatement();

			ResultSet rs = smt.executeQuery(sqlCnt);
			rs.next();
			Integer cnt = new Integer(rs.getInt("cnt"));
			req.setAttribute("cnt", cnt);

			int max = BookBean.PAGE_MAX;	// 1ページあたりの表示件数
			//
			if ("999999".equals(pageStr)) {
				double dMax = cnt / (double)max;
				int maxPage = (int)Math.ceil(dMax);
				pageStr = String.valueOf(maxPage);
			}
			//	検索結果の取得範囲（Ｌｉｍｉｔ）を準備
			if(pageStr == null) {
				page = 1;
			} else {
				page = Integer.parseInt(pageStr);
			}
			int start = (page - 1) * max;
			// 書籍情報取得SQL文
			String sql = "select * from books" + where + " order by id limit " + start + ", " + max;
System.out.println(String.format("pageStr: %s page: %d start:%d max: %d", pageStr, page, start, max));
			rs = smt.executeQuery(sql);

			List<BookBean> list = new ArrayList<BookBean>();

			while(rs.next()) {

				BookBean book = new BookBean();
				book.setId(rs.getInt("ID"));
				book.setTitle(rs.getString("TITLE"));
				book.setWriter(rs.getString("WRITER"));
				book.setPublisherId(rs.getInt("PUBLISHER_ID"));
				book.setGenreId(rs.getInt("GENRE_ID"));
				book.setPublicationDate(rs.getString("PUBLICATION_DATE"));
				book.setIsbn(rs.getString("ISBN"));
				book.setContent(rs.getString("CONTENT"));
				book.setPicture(rs.getString("PICTURE"));
				book.setDeleteFlag(rs.getInt("DELETE_FLAG"));
				book.setOpenFlag(rs.getInt("OPEN_FLAG"));
				book.setRentalId(rs.getInt("RENTAL_ID"));
				book.setNewestId(rs.getInt("NEWEST_ID"));

				list.add(book);
			}
			req.setAttribute("list", list);

		} catch(SQLException e) {
			throw new ServletException(e);
		} finally {
			if(smt != null) {
				try {
					smt.close();
				} catch(SQLException ignore) {
					// none
				}
			}
			if(con != null) {
				try {
					con.close();
				} catch(SQLException ignore) {
					// none
				}
			}
		}
		req.setAttribute("page", page);
		req.getRequestDispatcher("/book/userBookSearchResult.jsp").forward(req, resp);
	}

	// 全角スペースを半角スペースに変換し単語を配列に格納する処理
	public String[] convert(String param) {
		char[] c = {'\u3000'};
		String wspace = new String(c);
		param = param.replaceAll(wspace," ");

		return param.split(" ");
	}
}
